package com.lwj.liwanjia.view.activity.supermarket;


import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.KuaiDiAdapter;
import com.lwj.liwanjia.adapter.ShangPinAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.AddGwcBean;
import com.lwj.liwanjia.bean.KuaidiBean;
import com.lwj.liwanjia.bean.MarketDetailBean;
import com.lwj.liwanjia.impl.AddGwcView;
import com.lwj.liwanjia.impl.KuaidiView;
import com.lwj.liwanjia.impl.MarketDetailView;
import com.lwj.liwanjia.presenter.AddGwcPresenter;
import com.lwj.liwanjia.presenter.KuaidiPresenter;
import com.lwj.liwanjia.presenter.MarketDetailPresenter;
import com.lwj.liwanjia.utils.NetWorkUtil;
import com.lwj.liwanjia.utils.PopUtils;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.cuxiao.PromotionMoreActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 具体商品分类
 */
public class ShangPinActivity extends BaseActivity implements MarketDetailView, KuaidiView {
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_sales)
    TextView tvSales;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.height_price)
    ImageView heightPrice;
    @BindView(R.id.lower_price)
    ImageView lowerPrice;
    @BindView(R.id.tv_haopingdu)
    TextView tvHaopingdu;
    @BindView(R.id.tv_shaixuan)
    TextView tvShaixuan;
    @BindView(R.id.market_tab_rlv)
    SuperRecyclerView tabRlv;
    @BindView(R.id.progress)
    ProgressBar progressbar;


    private String type;//类型
    private TextView mTv;//当前tab标签
    private PopupWindow popupWindow;
    private int selection = 0;//选中快递的位置
    private List<String> kdList = new ArrayList<>();//快递方式
    private KuaiDiAdapter kuaiDiAdapter;
    private ViewHolder holder;
    private ShangPinAdapter apapter;
    private List<MarketDetailBean.DataBean> list = new ArrayList<>();
    private int shopInfoId;
    private MarketDetailPresenter presenter;
    private SpfUtils spfUtils;
    private String classify = "销量";//按照什么来排序
    private int sortType = 1;//价格（1为降序0为升序）
    private String expressType = "立马送";//快递类型
    private KuaidiPresenter kuaidiPresenter;
    private int isFirst = 0;

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            type = bundle.getString("type");
            shopInfoId = bundle.getInt("shopInfoId ");
        }
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText(type + "分类");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.mipmap.fenlei);
        mTv = tvSales;
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        tabRlv.setLayoutManager(manager);
        tabRlv.setRefreshEnabled(false);
        tabRlv.setLoadMoreEnabled(false);
        tabRlv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = getResources().getDimensionPixelOffset(R.dimen.x10);
                outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.x10);
                if (parent.getChildLayoutPosition(view) % 2 == 0) {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.x10);
                }
            }
        });
        apapter = new ShangPinAdapter(this, list);
        tabRlv.setAdapter(apapter);
        presenter = new MarketDetailPresenter(this);
        kuaidiPresenter = new KuaidiPresenter(this);
        clickListener();
    }

    //点击事件
    private void clickListener() {
        apapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                Intent intent = new Intent(ShangPinActivity.this, ShangpinDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("shopGoodsCode", list.get(position).getCommodityCode());
                bundle.putString("commodityType", list.get(position).getCommodityType());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initData() {
        presenter.getMarketDetailData(classify, shopInfoId, type, sortType, expressType);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shang_pin;
    }

    @OnClick({R.id.tv_left, R.id.iv_right, R.id.tv_sales, R.id.tv_price, R.id.tv_haopingdu, R.id.tv_shaixuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.iv_right://菜单
                PopUtils.getInstance().showPopupWindow(ShangPinActivity.this, ivRight);
                break;
            case R.id.tv_sales://销量
                switchTab(tvSales);
                selection = 0;
                classify = "销量";
                initData();
                break;
            case R.id.tv_price://价格
                if (isFirst == 0) {
                    switchTab(tvPrice);
                    heightPrice.setImageResource(R.mipmap.gao);
                    lowerPrice.setImageResource(R.mipmap.di);
                    selection = 0;
                    sortType = 0;
                    classify = "价格";
                    isFirst = 1;
                } else if (isFirst == 1) {
                    switchTab(tvPrice);
                    lowerPrice.setImageResource(R.mipmap.di_1);
                    heightPrice.setImageResource(R.mipmap.gao_1);
                    selection = 0;
                    sortType = 1;
                    classify = "价格";
                    isFirst = 0;
                }
                initData();
                break;
            case R.id.tv_haopingdu://好评度
                switchTab(tvHaopingdu);
                selection = 0;
                classify = "好评度";
                initData();
                break;
            case R.id.tv_shaixuan://筛选
                switchTab(tvShaixuan);
                classify = "筛选";
                kuaidiPresenter.getKuaidi();
                break;
        }
    }

    //弹出筛选popupWindow
    private void showPopupWindow() {
        final View popview = LayoutInflater.from(this).inflate(R.layout.popupwindow_layout, null);
        popupWindow = new PopupWindow(popview, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //设置弹出窗体不可点击
        popupWindow.setFocusable(true);
        //实例化一个ColorDrawable,点击窗体外部区域时消失
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setOutsideTouchable(true);
        //设置动画
        //   popupWindow.setAnimationStyle(R.style.PopupAnimation);
        //弹出位置
        popupWindow.showAsDropDown(tvShaixuan);
        holder = new ViewHolder(popview);
        kuaiDiAdapter = new KuaiDiAdapter(this, kdList);
        kuaiDiAdapter.setCheckPosition(selection);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        holder.rlvKuaidi.setLayoutManager(manager);
        holder.rlvKuaidi.setRefreshEnabled(false);
        holder.rlvKuaidi.setLoadMoreEnabled(false);
        holder.rlvKuaidi.setAdapter(kuaiDiAdapter);
        //快递方式
        kuaiDiAdapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                selection = position;
                kuaiDiAdapter.setCheckPosition(selection);
                kuaiDiAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                expressType = kdList.get(selection);
                initData();
            }
        });
    }

    /**
     * 切换tab标签
     *
     * @param tv
     */
    private void switchTab(TextView tv) {
        if (mTv != tv) {
            tv.setTextColor(getResources().getColor(R.color.colorWite));
            tv.setBackgroundColor(getResources().getColor(R.color.colorCECECE));
            mTv.setTextColor(getResources().getColor(R.color.colorC4C4C4));
            mTv.setBackgroundColor(getResources().getColor(R.color.colorWite));
            mTv = tv;
            if (tv != tvPrice) {
                heightPrice.setImageResource(R.mipmap.gao_1);
                lowerPrice.setImageResource(R.mipmap.di);
                isFirst = 0;
            }
        }
    }

    @Override
    public void showProgress() {
        progressbar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progressbar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败！", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void getKuaidi(KuaidiBean kuaidiBean) {
        List<String> data = kuaidiBean.getData();
        if (data.size() > 0) {
            kdList.clear();
            kdList.addAll(data);
            showPopupWindow();
        }

    }

    @Override
    public void getMarketDetailData(MarketDetailBean marketDetailBean) {
        if (marketDetailBean.getState() == 1) {
            list.clear();
            list.addAll(marketDetailBean.getData());
            apapter.notifyDataSetChanged();
        }
    }

    static class ViewHolder {
        @BindView(R.id.rlv_kuaidi)
        SuperRecyclerView rlvKuaidi;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter = null;
        }
        if (kuaidiPresenter != null) {
            kuaidiPresenter = null;
        }
    }
}
